#!/usr/bin/env python
# coding: utf-8

import optparse
import os
import types

# 对标准的 OptionParser 加入对 "必须" 选项的支持
import optparse

class Option (optparse.Option):
    ATTRS = optparse.Option.ATTRS + ['required']

    def _check_required (self):
        if self.required and not self.takes_value():
            raise OptionError(
                "required flag set for option that doesn't take a value",
                 self)

    # Make sure _check_required() is called from the constructor!
    CHECK_METHODS = optparse.Option.CHECK_METHODS + [_check_required]

    def process (self, opt, value, values, parser):
        optparse.Option.process(self, opt, value, values, parser)
        parser.option_seen[self] = 1


class OptionParser (optparse.OptionParser):
    def __init__(self, usage=None, option_list=None, option_class=Option,
                 version=None, conflict_handler='error', description=None,
                 formatter=None, add_help_option=True, prog=None, epilog=None) :
        optparse.OptionParser.__init__(self,usage=usage, option_list=option_list, option_class=Option,
                 version=version, conflict_handler=conflict_handler, description=description,
                 formatter=formatter, add_help_option=add_help_option, prog=prog, epilog=epilog)
        
        
    def _init_parsing_state (self):
        optparse.OptionParser._init_parsing_state(self)
        self.option_seen = {}

    def check_values (self, values, args):
        for option in self.option_list:
            if (isinstance(option, Option) and
                option.required and
                # not self.option_seen.has_key(option)):
                option not in self.option_seen):
                self.error("%s not supplied" % option)
        return (values, args)
    
    def check_exist(self, opt) :
        option = self.get_option(opt)

        # Assumes the option's 'default' is set to None!
        if getattr(self.values, option.dest) is None :
            return False
        
        return True
    

# test
if __name__ == '__main__' :
    parser = OptionParser()
    parser.add_option(
            "-j",
            "--job",
            type = "string",
            dest = "job_name",
            metavar = "NAME",
            help = 'the job that will be loaded',
            required = True
            )
        
    (options, args) = parser.parse_args()
    
    # print ("verbose:", options.verbose)
    print ("file:")